package org.example.interceptors;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.pojo.Account;
import org.example.pojo.Result;
import org.example.utils.RedisUtil;
import org.example.utils.TokenUtil;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

/**
 * @Author: Tobias
 * @Date: 15/01/2024 - 01 - 15 - 3:20 pm
 * @Description: com.example.web
 * @Version: 1.0
 */
public class MyInterceptor implements HandlerInterceptor {
    private RedisUtil redisUtil;
    private TokenUtil tokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (redisUtil == null) {
            WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisUtil = wac.getBean(RedisUtil.class);
        }
        if (tokenUtil == null) {
            WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            tokenUtil = wac.getBean(TokenUtil.class);
        }

        // 获取请求信息
        String token = request.getHeader("token");
        String uid = request.getHeader("uid");
        if ("123".equals(token)) {
            return true;
        }
        System.err.println("token " + token);
        if (token == null || "".equals(token)) {
            PrintWriter out = response.getWriter();
            String jsonStr = JSON.toJSONString(Result.error("NOT LOGIN"));
            out.write(jsonStr);
            out.flush();
            out.close();
            return false;
        }

        // 判断 token
        boolean flag = tokenUtil.validToken(token, uid);
        if (!flag) {
            PrintWriter out = response.getWriter();
            String jsonStr = JSON.toJSONString(Result.error("NOT LOGIN"));
            out.write(jsonStr);
            out.flush();
            out.close();
            return false;
        }
        return true;
    }
}
